# -*- coding: utf-8 -*-

import urllib

from flask import request, url_for, render_template, jsonify
import requests

from . import tb

URL_TRANSLATOR_URL = 'http://fanyi.baidu.com/transpage?query={}&source=url&ie=utf8&from=cht&to=zh&render=1'
TXT_TRANSLATOR_URL = 'http://fanyi.baidu.com/v2transapi'
SINA_SHORTEN_URL = 'https://api.weibo.com/2/short_url/shorten.json'

@tb.route('/info/<tb_word>/<desc>/', methods=['GET'])
def info(tb_word, desc=None):
    # desc = request.args.get('desc', '')
    img_url = request.args.get('img_url', '')
    img_url = url_for('tb.asset', filename=img_url)
    # tb_word = request.args.get('tb_word', '')
    return render_template('taokouling.html', desc=desc, img_url=img_url, tb_word=tb_word)


@tb.route('/gen_url/', methods=['POST'])
def gen_url():
    desc = request.form.get('desc', '')
    img_url = request.form.get('img', '')
    tb_word = request.form.get('tb_word', '')
    if not desc or not img_url or not tb_word:
        return jsonify({'code': u'传入参数错误'})

    trans_dict = {
        "from": "zh",
        "to": "cht",
        "query": desc
    }

    try:
        res = requests.post(TXT_TRANSLATOR_URL, data=trans_dict)
        desc = res.json()['trans_result']['data'][0]['dst']
    except:
        pass

    page_url = url_for('tb.info', desc=desc, img_url=img_url, tb_word=tb_word, _external=True)
    url_long = URL_TRANSLATOR_URL.format(page_url)

    try:
        res = requests.get(SINA_SHORTEN_URL, params={
            'source': tb.app.config['SINA_API_KEY'],
            'url_long': url_long
        })
        url_short = res.json()['urls'][0]['url_short']
    except:
        return jsonify({'code': u'短连接生成错误'})
    return jsonify({'url': url_short})
